package com.lrz.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lrz.dao.LikeMapper;
import com.lrz.pojo.Like;
import com.lrz.service.ArticleService;
import com.lrz.service.CommentService;
import com.lrz.service.LikeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class LikeServiceImpl implements LikeService {

    @Resource
    private LikeMapper likeMapper;

    @Resource
    private ArticleService articleService;

    @Resource
    private CommentService commentService;

    @Override
    public boolean isLike(String tid, Long userId) {
        QueryWrapper<Like> wrapper = new QueryWrapper<>();
        wrapper.eq("userid", userId);
        wrapper.eq("tid", tid);
        Like like = likeMapper.selectOne(wrapper);
        return like != null;
    }

    @Override
    public boolean articleThumbup(String tid, Long userId) {
        articleService.addThumbup(Long.valueOf(tid));
        return thumbup(tid,userId);
    }

    @Override
    public boolean articleDelThumbup(String tid, Long userId) {
        articleService.decThumbup(Long.valueOf(tid));
        return delThumbup(tid,userId);
    }

    @Override
    public boolean commentThumbup(String tid, Long userId) {
        commentService.addThumbup(tid);
        return thumbup(tid,userId);
    }

    @Override
    public boolean commentDelThumbup(String tid, Long userId) {
        commentService.decThumbup(tid);
        return delThumbup(tid,userId);
    }


    private boolean thumbup(String tid, Long userId) {
        Like like = new Like();
        like.setTid(tid);
        like.setUserid(userId);
        int i = likeMapper.insert(like);
        return i == 1;
    }


    private boolean delThumbup(String tid, Long userId) {
        QueryWrapper<Like> wrapper = new QueryWrapper<>();
        wrapper.eq("userid", userId);
        wrapper.eq("tid", tid);
        int i = likeMapper.delete(wrapper);
        return i == 1;
    }

}
